package xyz.coolcsm.security.filter;

import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import xyz.coolcsm.security.config.RsaKeyProperties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.Map;

/**
 * @author 什锦
 * @since 2021-06-1
 * 自定义登陆逻辑,前后端交互json格式
 */
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    //为了以后前端密码加密，后端解密使用
    private  RsaKeyProperties rsaKeyProperties;

    public void setRsaKeyProperties(RsaKeyProperties rsaKeyProperties) {
        this.rsaKeyProperties = rsaKeyProperties;
    }

    @SneakyThrows
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8")
            || request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){
            BufferedReader reader = request.getReader();
            String s = reader.readLine();
            String username = null;
            String password = null;
            String str1 = new String(Base64.encodeBase64(rsaKeyProperties.getPrivateKey().getEncoded()));
            Map<String,String> map = JSONObject.parseObject(s,Map.class);
            username = RsaUtils.decrypt(map.get("username"), str1);
            password = RsaUtils.decrypt(map.get("password"), str1);
            String code = map.get("code");
            String uuid = map.get("uuid");
            Integer left = Integer.valueOf(code);
            Integer o = (Integer)redisService.get(uuid);
            redisService.del(uuid);
            if (left<=o-8 || o+8<=left){
               throw new RuntimeException("验证码不合法");
            }
            if (username == null){

            }
            if (password == null){

            }
            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        return super.attemptAuthentication(request, response);
    }

}

